#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
#include <stdlib.h>

#include "recieve_t.hpp"

char* itoa(int,int);

void *launch_member_function(void * obj)
{
	recieve_t *ptr = reinterpret_cast<recieve_t *>(obj);
	return ptr->recieve_file();
}

recieve_t::recieve_t(int fd, char *name, int size)
{
	sockfd = fd;
	file_name = name;
	file_size = size;
	progress = new QProgressBar;
	progress->setMaximum(size);
	progress->setValue(0);

	char *ptr = ::itoa(size,10);
	QString str = file_name;
        str += " - ";
	str += ptr;
	str += " bytes";

	progress_info = new QLabel(str);
	progress_info->setWordWrap(true);
	progress_info->setAlignment(Qt::AlignCenter);

	layout = new QVBoxLayout;
	layout->addWidget(progress_info);
	layout->addWidget(progress);

	setLayout(layout);

	connect(this, SIGNAL(progress_bar(int)), progress, SLOT(setValue(int)));
	pthread_t t_rec;
	pthread_create(&t_rec, NULL, launch_member_function, this);
}

void *recieve_t::recieve_file()
{
	void *retval = NULL;
	std::cout << "starting to read file\n";
	int fd_out = ::creat(file_name, O_RDWR | S_IRWXU);
	int n = 0;
	const int SIZE = 2555;
	char buffer[SIZE];
	write(sockfd, "accept", 7);
	while(n = ::read(sockfd, buffer, SIZE))
	{
		if(n>0)
		{	::write(fd_out, buffer, n);
		this->e_progress_bar(n);}
	}

        ::close(sockfd);
        ::close(fd_out);
	return retval;
}
void recieve_t::e_progress_bar(int n)
{
	static int k = 0;
	k += n;
	emit progress_bar(k);
}
